package com.momoauth.api_client.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.RedisKeyCommands;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class RedisUtil {

    @Resource
    RedisTemplate<String, Object> redisTemplate;

    /**
     * 是否存在 key
     * @param key 键
     * @return java.lang.Boolean
     */
    public Boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 删除缓存
     * @param keys 键集合
     * @return void
     */
    public void del(String... keys) {
        redisTemplate.delete(Arrays.asList(keys));
    }

    /**
     * 获取缓存 TTL
     * @param key 键
     * @return java.lang.Long 时长（s）
     */
    public Long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    /**
     * 设置缓存 TTL
     * @param key  键
     * @param time 时长（s）
     */
    public void expire(String key, long time) {
        try {
            redisTemplate.expire(key, time, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error("set TTL key:{} time:{} fail ", key, time, e);
        }
    }


    /**
     * 添加缓存 - string
     * @param key   键
     * @param value 值
     */
    public void set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
        } catch (Exception e) {
            log.error("set STRING key:{} val:{} fail ", key, value, e);
        }
    }

    /**
     * 添加缓存 - string
     * @param key   键
     * @param value 值
     * @param time  ttl (s)
     */
    public void set(String key, Object value, long time) {
        try {
            redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error("set STRING key:{} val:{} ttl:{} fail ", key, value, time, e);
        }
    }

    /**
     * 获取缓存 - string
     * @param key 键
     * @return java.lang.Object
     */
    public Object get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 自增 - string
     * @param key  键
     * @param incr 增量
     * @return java.lang.Long 自增后值
     */
    public Long incr(String key, long incr) {
        return redisTemplate.opsForValue().increment(key, incr);
    }


    /**
     * 添加hash缓存 - hash
     * @param key   键
     * @param item  项
     * @param value 值
     */
    public void hSet(String key, Object item, Object value) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
        } catch (Exception e) {
            log.error("set HASH key:{} item:{} val:{} fail ", key, item, value, e);
        }
    }

    /**
     * 添加hash缓存 - hash
     * @param key 键
     * @param map 对应多个键
     */
    public void hSet(String key, Map<Object, Object> map) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
        } catch (Exception e) {
            log.error("set HASH key:{} map:{} fail ", key, map, e);
        }
    }

    /**
     * 获取hash缓存 - hash
     * @param key 键
     * @return Map<Object, Object>
     */
    public Map<Object, Object> hGet(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * 获取hash缓存 - hash
     * @param key  键
     * @param item 项
     * @return java.lang.Object
     */
    public Object hGet(String key, String item) {
        return redisTemplate.opsForHash().get(key, item);
    }

    /**
     * 删除hash缓存某项 - hash
     * @param key   键
     * @param items 项
     */
    public void hDel(String key, Object... items) {
        redisTemplate.opsForHash().delete(key, items);
    }

    /**
     * hash是否存在某项 - hash
     * @param key  键
     * @param item 项
     * @return java.lang.Boolean
     */
    public Boolean hHasKey(String key, String item) {
        return redisTemplate.opsForHash().hasKey(key, item);
    }

    /**
     * hash自增 - hash
     * @param key  键
     * @param item 项
     * @param incr 增量
     * @return long 自增后值
     */
    public long hIncr(String key, String item, long incr) {
        return redisTemplate.opsForHash().increment(key, item, incr);
    }


    /**
     * 添加set缓存 - set
     * @param key    键
     * @param values 值
     */
    public void sSet(String key, Object... values) {
        try {
            redisTemplate.opsForSet().add(key, values);
        } catch (Exception e) {
            log.error("set SET key:{} set:{} fail ", key, values, e);
        }
    }

    /**
     * 获set大小 - set
     * @param key 键
     * @return java.lang.Long
     */
    public Long sSize(String key) {
        return redisTemplate.opsForSet().size(key);
    }

    /**
     * 获取set缓存 - set
     * @param key 键
     * @return Set<Object>
     */
    public Set<Object> sGet(String key) {
        return redisTemplate.opsForSet().members(key);
    }

    /**
     * set是否存在某值 - set
     * @param key   键
     * @param value 值
     * @return java.lang.Boolean
     */
    public Boolean sHasKey(String key, Object value) {
        return redisTemplate.opsForSet().isMember(key, value);
    }

    /**
     * 从set中移除值 - set
     * @param key    键
     * @param values 值
     */
    public void sRemove(String key, Object... values) {
        redisTemplate.opsForSet().remove(key, values);
    }


    /**
     * 添加缓存 - list
     * @param key   键
     * @param value 值
     */
    public void lSet(String key, Object value) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
        } catch (Exception e) {
            log.error("set LIST key:{} val:{} fail ", key, value, e);
        }
    }

    /**
     * 添加缓存 - list
     * @param key    键
     * @param values 值集合
     */
    public void lSet(String key, Object... values) {
        try {
            redisTemplate.opsForList().rightPushAll(key, Arrays.asList(values));
        } catch (Exception e) {
            log.error("set LIST key:{} list:{} fail ", key, values, e);
        }
    }

    /**
     * 获取list缓存大小 - list
     * @param key 键
     * @return java.lang.Long
     */
    public Long lSize(String key) {
        return redisTemplate.opsForList().size(key);
    }

    /**
     * 获取list缓存区间 - list
     * @param key   键
     * @param start 起始
     * @param end   结束
     * @return List<Object>
     */
    public List<Object> lRange(String key, long start, long end) {
        return redisTemplate.opsForList().range(key, start, end);
    }

    /**
     * list缓存头插入列
     * @param key   键
     * @param value 值
     */
    public void lLeftPush(String key, Object value) {
        try {
            redisTemplate.opsForList().leftPush(key, value);
        } catch (Exception e) {
            log.error("LIST left push key:{} set:{} fail ", key, value, e);
        }
    }

    /**
     * list缓存尾插入列
     * @param key   键
     * @param value 值
     */
    public void lRightPush(String key, Object value) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
        } catch (Exception e) {
            log.error("LIST right push key:{} set:{} fail ", key, value, e);
        }
    }

    /**
     * list左出列
     * @param key     键
     * @param isBlock 是否阻塞
     * @return java.lang.Object
     */
    public Object lLeftPop(String key, boolean isBlock) {
        if (isBlock) {
            return redisTemplate.opsForList().leftPop(key, Integer.MAX_VALUE, TimeUnit.SECONDS);
        } else {
            return redisTemplate.opsForList().leftPop(key);
        }
    }

    /**
     * list右出列
     * @param key     键
     * @param isBlock 是否阻塞
     * @return java.lang.Object
     */
    public Object lRightPop(String key, boolean isBlock) {
        if (isBlock) {
            return redisTemplate.opsForList().rightPop(key, Integer.MAX_VALUE, TimeUnit.SECONDS);
        } else {
            return redisTemplate.opsForList().rightPop(key);
        }
    }


    /**
     * 获取所有正则匹配的key
     * @param pattern 正则
     * @return java.util.List<java.lang.String>
     */
    public List<String> getKeys(String pattern) {
        return redisTemplate.execute(connection -> {
            RedisKeyCommands command = connection.keyCommands();
            ScanOptions scanOpts = ScanOptions.scanOptions().match(pattern).count(100).build();
            Cursor<byte[]> cursor = command.scan(scanOpts);
            Set<String> set = new HashSet<>();
            while (cursor.hasNext()) {
                byte[] bytes = cursor.next();
                set.add(new String(bytes, StandardCharsets.UTF_8));
            }
            return new ArrayList<>(set);
        }, true);
    }
}
